package com.cloudcc.migrationToNewSys;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudcc.ccTool.CCObject;
import com.cloudcc.ccTool.CCService;
import com.cloudcc.ccTool.StringUtil;
import com.cloudcc.ccTool.UserInfo;

import java.util.*;

public class MobileLayoutMigration {
    public CCService cs;
    public UserInfo userInfo;
    private  MigrationCCService mcs;


    public MobileLayoutMigration(UserInfo userInfo) {
        this.userInfo = userInfo;
        cs = new CCService(userInfo);
        mcs = new MigrationCCService();
    }

    public static void main(String[] args) {
        UserInfo userInfo = new UserInfo();
        MobileLayoutMigration ta = new MobileLayoutMigration(userInfo);
        ta.Execute();//布局迁移执行方法
        ta.relatedListExecute();//相关列表迁移执行方法

    }

    /**
     * 获取所有对象的映射
     * <p>
     * 该方法旨在创建并返回一个包含特定对象名称与其对应ID的映射
     * 它首先定义了一组感兴趣的对象名称，然后通过查询数据库获取这些对象的详细信息，
     * 最终将每个对象的名称与其对应的ID一起存储在映射中并返回
     *
     * @return 包含对象名称与ID映射的Map对象
     */
    public Map allObject() {
        Set<String> data = new HashSet<>();
        data.add("u8ckda");
        
        // 初始化一个映射，用于存储对象名称与ID的对应关系
        Map<String, String> tableMap = new HashMap();
        // 构造查询语句，以获取对象的详细信息
        String objsql = "select datatable_name,schemetable_name,prefix,id,label from TP_SYS_OBJECT where schemetable_name in " + StringUtil.set2SqlIn(data) + "";
        // 执行查询并获取结果列表
        List<CCObject> dlist = cs.cqlQuery("TP_SYS_OBJECT", objsql);
        // 如果查询结果不为空，则遍历结果列表，提取并存储对象名称与ID的对应关系
        if (dlist.size() > 0) {
            for (CCObject ac : dlist) {
                String tablename = StringUtil.str(ac.get("schemetable_name"));
                String tableid = StringUtil.str(ac.get("id"));
                // 将对象名称与ID的对应关系存储在映射中
                tableMap.put(tablename, tableid);
            }
        }
        // 返回包含对象名称与ID映射的Map对象
        return tableMap;
    }

    // todo 布局迁移执行方法
    public void Execute() {
        System.out.println("布局迁移开始 =================== ");
        Map<String, String> tableMap = allObject();
        if (!tableMap.isEmpty()) {
            for (String key : tableMap.keySet()) {
                String value = StringUtil.str(tableMap.get(key));
                String msg = "";
                if (!"".equals(value)) {
                    msg = queryTableLayout(value, key);
                } else {
                    msg = "未查询ID";
                }
                System.out.println("Key: " + key + ", Value: " + value + " ==== " + msg);
            }
        }
        System.out.println("布局迁移结束 =================== ");
    }

    /**
     * TODO 生成对象ID
     * 该方法主要负责查询指定对象ID的移动布局信息，并根据查询结果进行处理
     *
     * @param objid 对象ID，用于查询表布局
     * @return 返回处理结果的字符串表示
     */
    public String queryTableLayout(String objid, String objname) {
        // 初始化消息字符串，用于存储处理过程中的消息
        String msg = "";
        // 初始化返回字符串，用于存储最终的返回结果
        String retStr = "";
        // 初始化列表，用于存储处理结果
        List<String> rList = new ArrayList<>();
        // 只查询移动布局
        // 构造SQL查询语句，查询移动布局的相关信息
        String sql = "select id,parentid,name from tp_sys_layout where OBJ_ID ='" + objid + "' AND parentid is null";

        // 执行查询，获取布局数据列表
        List<CCObject> dataList = cs.cqlQuery("tp_sys_layout", sql);
        // 检查查询结果是否非空且不为空列表
        if (dataList != null && dataList.size() > 0) {
            // 遍历查询结果，处理每个布局对象
            for (CCObject ac : dataList) {
                // 提取布局ID、父布局ID和布局名称
                String layid = StringUtil.str(ac.get("id"));//页面布局id - 移动布局id

                String layoutname = StringUtil.str(ac.get("name"));//布局名称

                // 拼装移动布局参数
                // 调用方法，为移动布局添加参数，并转换为JSON字符串
                JSONObject parObj = addLayoutParameters(objid, layid, objname);
                retStr = parObj.toJSONString();//拼接布局参数
                // 检查返回的JSON字符串是否非空
                if (!"".equals(retStr)) {
                    // 如果非空，调用保存布局的方法，并存储结果消息
                    String queryLayoutIdsql = "select id from tp_sys_layout where name='" + layoutname + "' and (select schemetable_name from TP_SYS_OBJECT where id=tp_sys_layout.obj_id )='" + objname + "' and parentid is null";
                    List<CCObject> ccObjects = mcs.cqlQuery("tp_sys_layout", queryLayoutIdsql);
                    if (ccObjects.size() > 0) {
                        String layoutid = StringUtil.str(ccObjects.get(0).get("id"));
                        JSONObject saveLayoutParam = new JSONObject();
                        saveLayoutParam.put("layoutId", layoutid);
                        saveLayoutParam.put("layoutJson", retStr);
                        saveLayoutParam.put("type", "mobile");
                        System.out.println("saveLayoutParam = " + saveLayoutParam);
                        msg = savelayout(saveLayoutParam.toString());
                    } else {
                        msg = "未找到布局-objId = " + objid + ", layoutName = " + layoutname;
                    }
//

                } else {
                    // 如果为空，设置消息表示未获取到页面布局字段
                    msg = "未获取到页面布局字段！";
                }
                // 构造包含PC布局ID、布局名称和处理消息的字符串，并添加到结果列表中
                String msg2 = "2222PC布局ID：" + layid + "，布局名称：" + layoutname + "，" + msg;
                rList.add(msg2);
            }
        }
        // 返回结果列表的字符串表示
        return rList.toString();
    }


    /**
     * 添加布局参数
     * 该方法用于构建和返回一个包含xjList布局参数的JSONObject
     * 它通过调用API获取布局信息，然后根据获取的数据构造一个新的布局JSON对象
     *
     * @param objid    对象ID，用于指定布局的对象
     * @param layoutid 布局ID，用于指定需要修改的布局
     * @return 返回一个包含xjList布局参数的JSONObject
     */
    public JSONObject addLayoutParameters(String objid, String layoutid, String objname) {
        // 返回 布局参数
        JSONObject layObj = new JSONObject();

        // API URL和参数构建
        String Purl = cs.gatewayUrl() + "/setup/api/modifyLayoutLightning/queryLayout";
        JSONObject parObj = new JSONObject();
        parObj.put("objId", objid);
        parObj.put("layoutId", layoutid);


        // 发送请求并解析响应
        String ObjStr = cs.CCPost(Purl, parObj.toString());

        JSONObject obj = JSONObject.parseObject(ObjStr);
        // 检查响应结果
        if (StringUtil.str2b(obj.getString("result"))) {
            JSONObject dataObj = obj.getJSONObject("data");
            JSONArray sections = dataObj.getJSONArray("sections");
            String bfid; // 新建部分编号
            // 处理sections数据
            if (sections != null && !sections.isEmpty()) {
                for (int i = 0; i < sections.size(); i++) {
                    JSONObject section = sections.getJSONObject(i);
                    JSONArray columns = section.getJSONArray("columns");
                    JSONArray mobileColumns = new JSONArray();
                    JSONArray mobileColumn = new JSONArray();
                    for (int j = 0; j < columns.size(); j++) {
                        JSONArray columnGroup = columns.getJSONArray(j);
                        for (int k = 0; k < columnGroup.size(); k++) {
                            JSONObject column = columnGroup.getJSONObject(k);
                            // 创建一个新的JSONObject实例，避免引用问题
                            JSONObject newColumn = new JSONObject(column);
                            String apiname = column.get("apiname") == null ? "" : column.get("apiname").toString();

                            String queryFiledIdSql = "SELECT t1.id FROM TP_SYS_SCHEMETABLE t1 WHERE t1.schemetable_id = (select id from tp_sys_object where schemetable_name='"+objname+"') and t1.schemefield_name = '" + apiname.toLowerCase() + "' ";

                            List<CCObject> dataList = mcs.cqlQuery("TP_SYS_SCHEMETABLE", queryFiledIdSql);
                            String fieldId = "";
                            if (dataList != null && dataList.size() > 0) {
                                fieldId = dataList.get(0).get("id").toString();
                            }
                            //替换id
                            newColumn.put("id", fieldId);
                            newColumn.put("lightningUrl", null);
                            mobileColumn.add(newColumn);
                            if (fieldId.equals("")) {
                                columnGroup.remove(column);
                            }

                        }
                    }mobileColumns.add(mobileColumn);
                    section.remove("columns");
                    section.put("columns", mobileColumns);
                    section.remove("canChangeColumns");
                    section.remove("sortOrder");
                    section.remove("canDeleteSection");
                    section.remove("categoriesAllowed");
                    section.remove("sectionId");
                    // bfid后拼i+1，不足三位前边补0
                    bfid = "ext-gen" + String.format("%03d", i + 1);
                    section.put("sectionId", bfid);
                }
            }
            layObj.put("sections", sections);
            System.out.println("layObj = " + layObj);

        }

        return layObj;
    }

    /**
     * 移动保存方法
     * 此方法用于将布局信息保存到CRM系统中它通过调用xjList接口来修改布局
     *
     * @param parStr 包含布局信息的字符串
     */
    public String savelayout(String parStr) {
        String errmsg = "";
        //  保存接口URL
        String Purl = mcs.gatewayUrl() + "/setup/api/modifyLayoutLightning/saveLayout";
        // 发送POST请求并获取响应
        String ObjStr = mcs.CCPost(Purl, parStr);
        // 打印响应结果，便于调试
//    System.out.println("ObjStr = " + ObjStr);
        // 解析响应的JSON对象
        JSONObject obj = JSONObject.parseObject(ObjStr);

        // 根据响应结果判断操作是否成功
        if (StringUtil.str2b(obj.getString("result"))) {
//            System.out.println("操作成功！");
            errmsg = "操作成功！";
        } else {
            // 获取并打印失败原因
            String returnInfo = StringUtil.str(obj.getString("returnInfo"));
//            System.out.println("操作失败-returnInfo = " + returnInfo);
            errmsg = "操作失败！" + returnInfo;
        }
        return errmsg;
    }

    /**
     * 执行相关列表方法
     * 该方法遍历所有对象的映射，对每个对象执行关联列表的查询并打印结果
     */
    public void relatedListExecute() {
        System.out.println("相关列表迁移开始 =================== ");
        // 获取所有对象的映射
        Map<String, String> tableMap = allObject();
        // 如果映射不为空，则遍历映射中的每个键值对
        if (!tableMap.isEmpty()) {
            for (String key : tableMap.keySet()) {
                // 获取当前键对应的值，并转换为字符串
                String value = StringUtil.str(tableMap.get(key));
                // 初始化消息字符串
                String msg = "";
                // 如果值不为空，则查询关联列表
                if (!"".equals(value)) {
                    msg = queryTableRelatedList(value, key);
                } else {
                    // 如果值为空，则设置消息为"未查询ID"
                    msg = "未查询ID";
                }
                // 打印查询结果或消息
                System.out.println("==== " + msg);
            }
        }
        System.out.println("相关列表迁移结束 =================== ");
    }

    public String queryTableRelatedList(String objid, String objname) {
        String msg = "";
        String retStr = "";
        List<String> rList = new ArrayList<>();
        //  OBJ_ID ='2024CE26C81BB99Ao41Q' ---  测试对象 ID
        // 只查询移动布局
        String sql = "select id,parentid,name from tp_sys_layout where OBJ_ID ='" + objid + "' AND parentid is null";
        List<CCObject> dataList = cs.cqlQuery("tp_sys_layout", sql);
        if (dataList != null && dataList.size() > 0) {
            for (CCObject ac : dataList) {
                String layid = StringUtil.str(ac.get("id"));//页面布局id - 移动布局id
                String layoutname = StringUtil.str(ac.get("name"));//布局名称
                //拼装布局参数
                msg = queryRelatedListByLayout(objid, layid, layoutname, objname);
                String msg2 = "11111PC布局ID：" + layid + "，布局名称：" + layoutname + "，" + msg;
                rList.add(msg2);
            }
        }
        return rList.toString();
    }


    /**
     * 根据布局查询相关列表
     * 该方法通过发送HTTP POST请求，查询与特定对象和布局相关的列表信息，并将结果以Map形式返回
     *
     * @param objid    对象ID，用于指定查询的对象
     * @param layoutid 布局ID，用于指定查询的布局
     * @return 返回一个Map，其中键是相关列表的ID，值是包含列表信息的JSONObject
     */
    public String queryRelatedListByLayout(String objid, String layoutid, String layoutname, String objectname) {
        String msg = "";
        String queryLayoutIdsql = "select id from tp_sys_layout where name='" + layoutname + "' and (select schemetable_name from TP_SYS_OBJECT where id=tp_sys_layout.obj_id )='" + objectname + "' and parentid is null";
        String queryMobileLayoutSql = "select id,parentid,name from tp_sys_layout where name='" + layoutname + "' and (select schemetable_name from TP_SYS_OBJECT where id=tp_sys_layout.obj_id )='" + objectname + "' and parentid is not null";
        List<CCObject> mobileLayoutList = mcs.cqlQuery("tp_sys_layout", queryMobileLayoutSql);
        String mobilelayid ="";
        if (mobileLayoutList.size() > 0) {
             mobilelayid = StringUtil.str(mobileLayoutList.get(0).get("id"));//迁移后的布局ID
        }


        List<CCObject> ccObjects = mcs.cqlQuery("tp_sys_layout", queryLayoutIdsql);
        if (ccObjects.size() > 0) {
            String layid = StringUtil.str(ccObjects.get(0).get("id"));//迁移后的布局ID


            // 初始化一个Map，用于存储相关列表的信息
            // 定义CRM系统的API URL，用于查询布局相关的列表信息
            String Purl = cs.gatewayUrl() + "/setup/api/modifyLayoutLightning/queryRelatedListByLayout";

            // 创建一个空的JSON对象，用于封装请求参数
            JSONObject parObj = new JSONObject();
            // 将对象ID和布局ID放入请求参数中
            parObj.put("objId", objid);
            parObj.put("layoutId", layoutid);

            // 发送POST请求并获取响应
            String ObjStr = cs.CCPost(Purl, parObj.toString());
            // 解析响应字符串为JSON对象
            JSONObject obj = JSONObject.parseObject(ObjStr);
            // 检查响应结果是否成功
            if (StringUtil.str2b(obj.getString("result"))) {
                // 获取响应数据中的对象
                JSONObject dataObj = obj.getJSONObject("data");
                JSONArray layoutData = dataObj.getJSONArray("layoutData");
                //查询当前布局显示的相关列表id存入数组中
                String sql1 = "SELECT id FROM tp_sys_relatedlist where is_show=1 and layout_id='" + layoutid + "' order by seq";
                List<CCObject> dataList1 = cs.cqlQuery("tp_sys_relatedlist", sql1);//查出来所有相关列表id和相关对象api
                //定义一个空的String数组
                String[] idArray = new String[dataList1.size()];
                for (int j = 0; j < dataList1.size(); j++) {
                    idArray[j] = StringUtil.str(dataList1.get(j).get("id"));
                }
                for (int i = 0; i < layoutData.size(); i++) {
                    JSONObject layout = layoutData.getJSONObject(i);
                    JSONArray relatedLists = layout.getJSONArray("relatedLists");
                    for (int j = 0; j < relatedLists.size(); j++) {
                        JSONObject relatedList = relatedLists.getJSONObject(j);
                        String relatedListId = relatedList.getString("id"); //老的相关列表id
                        if (!Arrays.asList(idArray).contains(relatedListId)) {
                            // 如果relatedList的id不在idArray中，从layoutData中删除该对象
                            layoutData.remove(i);
                            i--; // 调整索引以避免跳过下一个元素
                            break; // 退出当前循环，因为当前layout已经被删除
                        } else {
                            //如果存在该id，拼配新系统的相关列表id
                            String queryObjname = "SELECT (select schemetable_name from TP_SYS_OBJECT  where id=tp_sys_relatedlist.obj_id) objname  FROM tp_sys_relatedlist where  id='" + relatedListId + "'";
                            List<CCObject> queryObjCCO = cs.cqlQuery("tp_sys_relatedlist", queryObjname);
                            String objname = "";//获得对象名
                            if (queryObjCCO.size() > 0) {
                                objname = StringUtil.str(queryObjCCO.get(0).get("objname"));
                            }
                            String queryNewsql = "SELECT id FROM tp_sys_relatedlist where  (select schemetable_name from TP_SYS_OBJECT  where id=tp_sys_relatedlist.obj_id) ='" + objname + "' and layout_id='" + mobilelayid + "'";
                            List<CCObject> queryNewCCO = mcs.cqlQuery("tp_sys_relatedlist", queryNewsql);
                            if (queryNewCCO.size() > 0) {
                                String newRelatedListId = StringUtil.str(queryNewCCO.get(0).get("id"));
                                relatedList.put("id", newRelatedListId);
                            }

                        }
                        JSONArray selectableColumns = relatedList.getJSONArray("selectableColumns");
                        for (int k = 0; k < selectableColumns.size(); k++) {
                            JSONObject column = selectableColumns.getJSONObject(k);
                            // 生成一个随机数并替换filterColumn
                            String filterColumn = StringUtil.str(column.get("filterColumn"));
                            String queryFiledSql = "SELECT schemetable_name objname,schemefield_name apiname FROM TP_SYS_SCHEMETABLE where id='" + filterColumn + "'";
                            //查询出该字段的字段API
                            List<CCObject> dataList = cs.cqlQuery("TP_SYS_SCHEMETABLE", queryFiledSql);
                            if (dataList != null && dataList.size() > 0) {
                                String apiname = StringUtil.str(dataList.get(0).get("apiname"));
                                String objname = StringUtil.str(dataList.get(0).get("objname"));
                                // 查询将要迁移系统的对应字段ID
                                String queryFiledIdSql = "SELECT id FROM TP_SYS_SCHEMETABLE where schemetable_name='" + objname + "' and schemefield_name='" + apiname.toLowerCase() + "'";
                                List<CCObject> dataList2 = mcs.cqlQuery("TP_SYS_SCHEMETABLE", queryFiledIdSql);
                                if (dataList2 != null && dataList2.size() > 0) {
                                    String fieldId = StringUtil.str(dataList2.get(0).get("id"));
                                    column.put("filterColumn", fieldId);
                                }
                            }

                        }
                    }
                }
                JSONObject processedData = processLayoutData(dataObj);//处理数据，处理成保存相关列表需要的格式
                String retStr = processedData.toJSONString();//拼接布局参数
                if (!"".equals(retStr)) {
//                // 如果非空，调用保存布局的方法，并存储结果消息
                    JSONObject saveLayoutParam = new JSONObject();
                    saveLayoutParam.put("layoutId", layid);
                    saveLayoutParam.put("layoutJson", retStr);
                    saveLayoutParam.put("type", "mobile");
                    System.out.println("saveLayoutParam = " + saveLayoutParam);
                    msg = saveRelatedList(saveLayoutParam.toString());

                } else {
                    // 如果为空，设置消息表示未获取到页面布局字段
                    msg = "未获取到页面布局字段！";
                }


            }
        } else {
            msg = "未找到布局-objId = " + objid + ", layoutName = " + layoutname;
        }
        return msg;
    }

    public JSONObject processLayoutData(JSONObject dataObj) {
        JSONArray layoutData = dataObj.getJSONArray("layoutData");
        JSONArray relatedLists = new JSONArray();

        for (int i = 0; i < layoutData.size(); i++) {
            JSONObject layout = layoutData.getJSONObject(i);
            JSONArray lists = layout.getJSONArray("relatedLists");

            for (int j = 0; j < lists.size(); j++) {
                JSONObject list = lists.getJSONObject(j);
                JSONObject processedList = new JSONObject();
                processedList.put("id", list.getString("id"));
                processedList.put("sortDesc", list.getBoolean("sortDesc"));
                processedList.put("sortColumn", list.getString("sortColumn"));
                processedList.put("customizedColumns", extractCustomizedColumns(list));
                processedList.remove("customListButtonsAdded");
                processedList.remove("stdListButtonsRevoked");
                JSONArray objects = new JSONArray();
                JSONArray customListButtonsAdded = list.getJSONArray("customListButtonsAdded");
                if (customListButtonsAdded != null) {
                    //取到stdListButtonsRevoked所有的key
                    for (int k = 0; k < customListButtonsAdded.size(); k++) {
                        String oldButtonId = StringUtil.str(customListButtonsAdded.getString(k));
                        String queryButtonNameSql = "SELECT label,(select schemetable_name from TP_SYS_OBJECT where id=TP_SYS_BUTTON.obj_id) objname  FROM TP_SYS_BUTTON where id='" + oldButtonId + "'";
                        List<CCObject> dataList = cs.cqlQuery("TP_SYS_BUTTON", queryButtonNameSql);
                        if (dataList != null && dataList.size() > 0) {
                            String buttonName = StringUtil.str(dataList.get(0).get("label"));
                            String objname = StringUtil.str(dataList.get(0).get("objname"));
                            String queryNewSysButtonIdSql = "SELECT id FROM TP_SYS_BUTTON where label='" + buttonName + "' and (select schemetable_name from TP_SYS_OBJECT where id=TP_SYS_BUTTON.obj_id)='" + objname + "'";
                            List<CCObject> dataList2 = mcs.cqlQuery("TP_SYS_BUTTON", queryNewSysButtonIdSql);
                            if (dataList2 != null && dataList2.size() > 0) {
                                String newButtonId = StringUtil.str(dataList2.get(0).get("id"));
                                objects.add(newButtonId);
                            }
                        }
                    }
                }
                processedList.put("customListButtonsAdded", objects);
//                processedList.put("customListButtonsAdded", new JSONArray());
                JSONObject stdListButtonsRevoked = list.getJSONObject("stdListButtonsRevoked");
                if (stdListButtonsRevoked != null) {
                    //取到stdListButtonsRevoked所有的key
                    Set<String> keySet = stdListButtonsRevoked.keySet();
                    JSONObject ButtonsRevoked = new JSONObject();
                    for (String key : keySet) {//取到了所有的key
                        String queryButtonNameSql = "SELECT label,(select schemetable_name from TP_SYS_OBJECT where id=TP_SYS_BUTTON.obj_id) objname  FROM TP_SYS_BUTTON where id='" + key + "'";
                        List<CCObject> dataList = cs.cqlQuery("TP_SYS_BUTTON", queryButtonNameSql);
                        if (dataList != null && dataList.size() > 0) {
                            String buttonName = StringUtil.str(dataList.get(0).get("label"));
                            String objname = StringUtil.str(dataList.get(0).get("objname"));
                            String queryNewSysButtonIdSql = "SELECT id FROM TP_SYS_BUTTON where label='" + buttonName + "' and (select schemetable_name from TP_SYS_OBJECT where id=TP_SYS_BUTTON.obj_id)='" + objname + "'";
                            List<CCObject> dataList2 = mcs.cqlQuery("TP_SYS_BUTTON", queryNewSysButtonIdSql);
                            if (dataList2 != null && dataList2.size() > 0) {
                                String newButtonId = StringUtil.str(dataList2.get(0).get("id"));
                                ButtonsRevoked.put(newButtonId, true);
                            }
                        }
                    }
//                    processedList.put("stdListButtonsRevoked", ButtonsRevoked);
                    processedList.put("stdListButtonsRevoked", new JSONObject());
                }
                processedList.put("seq", relatedLists.size() + 1);
                relatedLists.add(processedList);
            }
        }
        JSONObject result = new JSONObject();
        result.put("relatedLists", relatedLists);
        return result;
    }

    private static JSONArray extractCustomizedColumns(JSONObject list) {
        JSONArray selectableColumns = list.getJSONArray("selectableColumns");
        JSONArray customizedColumns = new JSONArray();
        for (int k = 0; k < selectableColumns.size(); k++) {
            JSONObject column = selectableColumns.getJSONObject(k);
            customizedColumns.add(column.getString("filterColumn"));
        }
        return customizedColumns;
    }

    /**
     * 保存移动布局相关列表的信息
     * 该方法通过发送HTTP POST请求来保存相关列表的信息，并根据响应结果判断操作是否成功
     *
     * @param parStr 包含要保存的相关列表信息的字符串
     * @return 返回一个字符串，表示操作结果
     */
    public String saveRelatedList(String parStr) {
        // 初始化错误消息为空字符串
        String errmsg = "";

        // 定义布局相关列表保存的API URL
        String purl = mcs.gatewayUrl() + "/setup/api/modifyLayoutLightning/saveRelatedList";

        // 发送POST请求并获取响应
        String ObjStr = mcs.CCPost(purl, parStr);
        System.out.println("ObjStr = " + ObjStr);

        // 解析响应的JSON对象
        JSONObject obj = JSONObject.parseObject(ObjStr);

        // 根据响应结果判断操作是否成功
        if (StringUtil.str2b(obj.getString("result"))) {
//            System.out.println("操作成功！");
            errmsg = "操作成功！";
        } else {
            // 获取并打印失败原因
            String returnInfo = StringUtil.str(obj.getString("returnInfo"));
//            System.out.println("操作失败-returnInfo = " + returnInfo);
            errmsg = "操作失败！" + returnInfo;
        }
        // 返回操作结果
        return errmsg;
    }

    public void buttonExecute() {
        System.out.println("按钮迁移开始 =================== ");
        Map<String, String> tableMap = allObject();
        if (!tableMap.isEmpty()) {
            for (String key : tableMap.keySet()) {
                String value = StringUtil.str(tableMap.get(key));
                String msg = "";
                if (!"".equals(value)) {
                    msg = queryButtonLayout(value, key);
                } else {
                    msg = "未查询ID";
                }
                System.out.println("Key: " + key + ", Value: " + value + " ==== " + msg);

            }
        }
        System.out.println("按钮迁移结束 =================== ");
    }

    public String queryButtonLayout(String objid, String objname) {
        // 初始化消息字符串，用于存储处理过程中的消息
        String msg = "";
        String retStr = "";
        // 初始化列表，用于存储处理结果
        List<String> rList = new ArrayList<>();
        // 只查询移动布局
        // 构造SQL查询语句，查询布局的相关信息
        String sql = "select id,parentid,name from tp_sys_layout where OBJ_ID ='" + objid + "' AND parentid is null";

        // 执行查询，获取布局数据列表
        List<CCObject> dataList = cs.cqlQuery("tp_sys_layout", sql);
        // 检查查询结果是否非空且不为空列表
        if (dataList != null && dataList.size() > 0) {
            // 遍历查询结果，处理每个布局对象
            for (CCObject ac : dataList) {
                // 提取布局ID、父布局ID和布局名称
                String layid = StringUtil.str(ac.get("id"));//页面布局id - 移动布局id

                String layoutname = StringUtil.str(ac.get("name"));//布局名称

                // 拼装移动布局参数
                // 调用方法，为移动布局添加参数，并转换为JSON字符串
                JSONObject parObj = addButtonParameters(objid, layid, objname);
                retStr = parObj.toJSONString();//拼接布局参数
//                // 检查返回的JSON字符串是否非空
                if (!"".equals(retStr)) {
                    // 如果非空，调用保存布局的方法，并存储结果消息
                    String queryLayoutIdsql = "select id from tp_sys_layout where name='" + layoutname + "' and (select schemetable_name from TP_SYS_OBJECT where id=tp_sys_layout.obj_id )='" + objname + "' and parentid is null";
                    List<CCObject> ccObjects = mcs.cqlQuery("tp_sys_layout", queryLayoutIdsql);
                    if (ccObjects.size() > 0) {
                        String layoutid = StringUtil.str(ccObjects.get(0).get("id"));
                        JSONObject saveLayoutParam = new JSONObject();
                        saveLayoutParam.put("layoutId", layoutid);
                        saveLayoutParam.put("layoutJson", retStr);
                        saveLayoutParam.put("type", "mobile");
                        msg = saveButton(saveLayoutParam.toString());
                    } else {
                        msg = "未找到布局-objId = " + objid + ", layoutName = " + layoutname;
                    }
//

                } else {
                    // 如果为空，设置消息表示未获取到页面布局字段
                    msg = "未获取到页面布局字段！";
                }
                // 构造包含PC布局ID、布局名称和处理消息的字符串，并添加到结果列表中
                String msg2 = "2222PC布局ID：" + layid + "，布局名称：" + layoutname + "，" + msg;
                rList.add(msg2);
            }
        }
        // 返回结果列表的字符串表示
        return rList.toString();
    }

    public JSONObject addButtonParameters(String objid, String layoutid, String objname) {
        // 返回 布局参数
        JSONObject layObj = new JSONObject();

        // API URL和参数构建
        String Purl = cs.gatewayUrl() + "/setup/api/modifyLayoutLightning/queryLayoutButton";
        JSONObject parObj = new JSONObject();
        parObj.put("objId", objid);
        parObj.put("layoutId", layoutid);
        // 发送请求并解析响应
        String ObjStr = cs.CCPost(Purl, parObj.toString());

        JSONObject obj = JSONObject.parseObject(ObjStr);
        // 检查响应结果
        if (StringUtil.str2b(obj.getString("result"))) {
            JSONObject dataObj = obj.getJSONObject("data");
            JSONArray buttonList = dataObj.getJSONArray("buttonList");
            // 处理sections数据
            JSONArray customButton = new JSONArray();
            JSONArray standardButton = new JSONArray();

            if (buttonList != null && !buttonList.isEmpty()) {
                for (int i = 0; i < buttonList.size(); i++) {
                    JSONObject button = buttonList.getJSONObject(i);
                    String buttonid = button.getString("id");
                    String event = StringUtil.str(button.getString("event"), "");
                    String unused = StringUtil.str(button.getString("unused"), "");
                    String queryButtonSql = "SELECT label FROM TP_SYS_BUTTON where id='" + buttonid + "'";
                    List<CCObject> buttoncco = cs.cqlQuery("TP_SYS_BUTTON", queryButtonSql);
                    String label = "";
                    if (buttoncco.size() > 0) {
                        label = StringUtil.str(buttoncco.get(0).get("label"));
                    }
                    String queryNewButtonSql = "SELECT id FROM TP_SYS_BUTTON where label='" + label + "' and (select schemetable_name from TP_SYS_OBJECT where id=TP_SYS_BUTTON.obj_id)='" + objname + "'";
                    List<CCObject> newbuttoncco = mcs.cqlQuery("TP_SYS_BUTTON", queryNewButtonSql);
                    String newbuttonid = "";
                    if (newbuttoncco.size() > 0) {
                        newbuttonid = StringUtil.str(newbuttoncco.get(0).get("id"));
                    }
                    if (!newbuttonid.equals("") && unused.equals("1")) {
                        if (!event.equals("URL")) {
                            customButton.add(newbuttonid);
                        } else if (event.equals("URL")) {
                            standardButton.add(newbuttonid);
                        }
                    }
                }
            }
            layObj.put("buttonsAdded", customButton);
            layObj.put("buttonsRevoked", standardButton);
        }

        return layObj;
    }

    public String saveButton(String parStr) {
        String errmsg = "";
        //  保存接口URL
        String Purl = mcs.gatewayUrl() + "/setup/api/modifyLayoutLightning/saveButtonLayout";
        // 发送POST请求并获取响应
        String ObjStr = mcs.CCPost(Purl, parStr);
        // 打印响应结果，便于调试
//    System.out.println("ObjStr = " + ObjStr);
        // 解析响应的JSON对象
        JSONObject obj = JSONObject.parseObject(ObjStr);

        // 根据响应结果判断操作是否成功
        if (StringUtil.str2b(obj.getString("result"))) {
//            System.out.println("操作成功！");
            errmsg = "操作成功！";
        } else {
            // 获取并打印失败原因
            String returnInfo = StringUtil.str(obj.getString("returnInfo"));
//            System.out.println("操作失败-returnInfo = " + returnInfo);
            errmsg = "操作失败！" + returnInfo;
        }
        return errmsg;
    }



}
